<template>
  <div class="sign-contract-page">
    <el-row :gutter="20">
      <!-- 左侧表单（仅修改合同编号输入框） -->
      <el-col :span="14">
        <div class="form-header">
          <div class="section-title">
            <i class="el-icon-star-on text-red"></i>
            签约办理
            <i class="el-icon-info text-blue ml-4"></i>
          </div>
        </div>

        <!-- 表单主体 -->
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="formRef" 
          label-width="100px" 
          class="form-container"
        >
          <!-- 合同编号：改为只读，自动生成HT开头编号 -->
          <el-form-item label="合同编号" prop="contractNo">
            <el-input 
              v-model="form.contractNo" 
              placeholder="自动生成HT开头编号" 
              readonly 
              style="background: #f5f5f5;"
            />
            <!-- <div class="el-form-item__tip">编号规则：HT + 时间戳 + 随机数（自动生成，不可修改）</div> -->
          </el-form-item>

          <!-- 其他表单项完全不变 -->
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="form.contractName" maxlength="30" show-word-limit placeholder="请输入合同名称" />
          </el-form-item>

          <el-form-item label="丙方名称" prop="partyCName">
            <el-input v-model="form.partyCName" maxlength="20" show-word-limit placeholder="请输入丙方名称" />
          </el-form-item>

          <el-form-item label="合同时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="date"
              placeholder="开始日期"
              style="width: 48%; margin-right: 4%;"
            />
            <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="结束日期"
              style="width: 48%;"
            />
          </el-form-item>

          <el-form-item label="上传合同" prop="agreementUrl">
            <el-upload
              class="pdf-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :limit="1"
              accept=".pdf"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
            >
              <el-button type="primary">上传PDF文件（≤60M）</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持 PDF 格式，大小不超过 60MB</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>

        <div class="bottom-actions">
          <el-button plain @click="handleCancel">返回</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </el-col>

      <!-- 右侧操作记录（完全不变） -->
      <el-col :span="10">
        <div class="operation-record-panel">
          <div class="panel-title">操作记录</div>
          <div class="record-list">
            <div v-for="(record, index) in operationRecords" :key="index" class="record-item">
              <div class="record-header">
                <span class="task-name">{{ record.action }}</span>
                <span class="end-time">{{ record.endTimeText }}</span>
              </div>
              <div class="record-operator">{{ record.operator }}（{{ record.statusText }}）</div>
            </div>
            <div v-if="operationRecords.length === 0" class="empty-record">暂无操作记录</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { useRoute, useRouter } from 'vue-router'
import { sign, getApprovalRecord } from '@/api/checkInApply/checkInApply'

// ===== 路由与表单 =====
const route = useRoute()
const router = useRouter()

const formRef = ref(null)
const fileList = ref([])

// 表单数据模型
const form = reactive({
  contractNo: '', // 自动生成HT开头编号
  contractName: '',
  partyCName: '',
  startTime: '',
  endTime: '',
  agreementUrl: '',
  bussinessId: '', // 流程实例id
  taskId: '' // 任务id
})

// 上传配置（不变）
const uploadUrl = 'http://localhost:8080/common/upload'
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }

// 上传事件（不变）
const handleUploadSuccess = (res, file) => {
  if (res.code === 200) {
    form.agreementUrl = res.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}
const handleUploadError = () => ElMessage.error('上传失败，请重试')
const beforeUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt60M = file.size / 1024 / 1024 < 60
  if (!isPDF) ElMessage.error('只能上传 PDF 文件')
  if (!isLt60M) ElMessage.error('文件大小不能超过 60MB')
  return isPDF && isLt60M
}

// 表单校验规则（contractNo保留必填，因自动生成后有值）
const rules = {
  contractNo: [{ required: true, message: '合同编号自动生成中，请稍候', trigger: 'blur' }],
  contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  partyCName: [{ required: true, message: '请输入丙方名称', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  agreementUrl: [{ required: true, message: '请上传合同文件', trigger: 'change' }]
}

// 核心：生成HT开头的唯一合同编号
const generateContractNo = () => {
  const prefix = 'HT' // 固定前缀
  const timestamp = new Date().getTime() // 时间戳（精确到毫秒，保证唯一性）
  const randomNum = Math.floor(Math.random() * 1000) // 3位随机数（进一步降低重复概率）
  const randomStr = randomNum.toString().padStart(3, '0') // 补零为3位，如001、099
  return `${prefix}${timestamp}${randomStr}`
}

// 操作记录相关（不变）
const operationRecords = reactive([])
const staticRecords = [
  {
    action: '发起申请 - 入住申请',
    operator: '顾廷烨',
    endTime: '2025-10-18 09:00:00',
    endTimeText: '2025-10-18 09:00:00',
    statusText: '已完成'
  },
  {
    action: '签约办理',
    operator: '法务人员',
    endTime: null,
    endTimeText: '正在处理',
    statusText: '正在处理'
  }
]

const formatRecord = (apiItem) => {
  const taskInfo = apiItem.taskInfo || {};
  const userInfo = apiItem.userInfo || {};
  const hasEndTime = !!taskInfo.endTime;
  const endTimeText = hasEndTime
    ? new Date(taskInfo.endTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    : '正在处理';
  const statusText = hasEndTime ? '已完成' : '正在处理';
  return {
    action: taskInfo.name || '未知操作',
    operator: userInfo.userName || '未知用户',
    endTime: taskInfo.endTime,
    endTimeText: endTimeText,
    statusText: statusText
  };
};

// 初始化：生成合同编号 + 加载流程信息 + 操作记录
onMounted(() => {
  // 1. 自动生成合同编号（页面加载时立即生成）
  form.contractNo = generateContractNo()
  
  // 2. 获取流程参数（不变）
  form.bussinessId = route.query.processInstanceId || '';
  form.taskId = route.query.taskId || '';

  // 3. 加载操作记录（不变）
  getApprovalRecord({ businessId: form.bussinessId })
    .then((res) => {
      if (res.code === 200 && res.data.length) {
        operationRecords.length = 0;
        res.data.forEach((apiItem) => {
          operationRecords.push(formatRecord(apiItem));
        });
      } else {
        operationRecords.push(...staticRecords.map(record => formatRecord(record)));
      }
    })
    .catch((err) => {
      console.error('获取操作记录失败：', err);
      ElMessage.warning('操作记录加载失败，显示默认记录');
      operationRecords.push(...staticRecords.map(record => formatRecord(record)));
    });
});

// 提交逻辑（不变）
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请完成所有必填项');
      return;
    }

    try {
      const res = await sign(form);
      if (res.code === 200) {
        ElMessage.success('签约办理成功');
        const newRecord = {
          action: '签约办理-提交',
          operator: '当前用户',
          endTime: new Date().toISOString(),
          endTimeText: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-'),
          statusText: '已完成'
        };
        operationRecords.unshift(newRecord);
        router.push('/CollaborationWork/tasking');
      } else {
        ElMessage.error(res.msg || '提交失败');
      }
    } catch (e) {
      ElMessage.error('请求失败');
    }
  });
};

// 返回按钮（不变）
const handleCancel = () => {
  ElMessageBox.confirm('确定返回吗？未保存的内容将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.back();
  });
};
</script>

<style scoped>
/* 原有样式不变，新增提示文字样式 */
.sign-contract-page {
  padding: 20px;
  background: #fff;
}
.form-header {
  margin-bottom: 16px;
}
.section-title {
  font-size: 16px;
  font-weight: 700;
  color: #333;
  display: flex;
  align-items: center;
}
.text-red { color: #ff4d4f; }
.text-blue { color: #409eff; }
.form-container {
  background: #fafafa;
  padding: 24px;
  border-radius: 4px;
  margin-bottom: 24px;
}
.operation-record-panel {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-top: 36px;
}
.panel-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}
.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}
.pdf-uploader {
  width: 100%;
}
.record-list {
  width: 100%;
}
.record-item {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}
.task-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  max-width: 70%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.end-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}
.record-operator {
  font-size: 13px;
  color: #666;
}
.empty-record {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 新增：合同编号提示文字样式 */
.el-form-item__tip {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}
</style>